package com.koron.operation.dispatch.service.imp;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import com.koron.common.core.config.ThreadLocalContext;
import com.koron.common.core.util.CodeTools;
import com.koron.common.core.util.StringUtils;
import com.koron.operation.dispatch.bean.*;
import com.koron.operation.dispatch.bean.dto.AccidentDto;
import com.koron.operation.dispatch.bean.dto.EquipmentDto;
import com.koron.operation.dispatch.bean.dto.HistoryListDto;
import com.koron.operation.dispatch.bean.dto.UnitSynDto;
import com.koron.operation.dispatch.bean.vo.AffectedLineVo;
import com.koron.operation.dispatch.bean.vo.AffectedTranVo;
import com.koron.operation.dispatch.bean.vo.AffectedUnitVo;
import com.koron.operation.dispatch.enums.EquipmentEnum;
import com.koron.operation.dispatch.mapper.AffectedLineMapper;
import com.koron.operation.dispatch.mapper.EquipmentAccidentMapper;
import com.koron.operation.dispatch.mapper.EquipmentDeMapper;
import com.koron.operation.dispatch.mapper.EquipmentHistoryMapper;
import com.koron.operation.dispatch.service.EquipmentRunService;
import com.koron.operation.startlog.mapper.StartLogBeanMapper;
import com.koron.operation.startlog.services.StartLogService;
import lombok.extern.slf4j.Slf4j;
import org.koron.ebs.mybatis.SessionFactory;
import org.koron.ebs.mybatis.TaskAnnotation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import static com.koron.common.core.util.DateAndTimeUtils.*;
import static com.koron.operation.dispatch.enums.OverhaulStatusEnum.*;

@Slf4j
@Service
public class EquipmentRunServiceDeImp implements EquipmentRunService {

    private String getCurrDs() {
        return ThreadLocalContext.get().getCurrDs();
    }

    private static final BigDecimal convertTime = BigDecimal.valueOf(1000 * 60 * 60d);//一小时毫秒数


    @Autowired
    private StartLogService startlogservice;


    @Override
    @TaskAnnotation("saveOrUpdate")
    public String saveOrUpdate(SessionFactory factory, List<EquipmentBean> synlist) {

        EquipmentDeMapper mapper = factory.getMapper(EquipmentDeMapper.class);

        List<EquipmentBaseBean> oldlist = mapper.queryAll();
        // 泵站顺序
        Map<String, Integer> deptSortmap = oldlist.stream()
                .filter(o -> ObjectUtil.isAllNotEmpty(o.getDeptSort(), o.getSort()))
                .collect(Collectors.toMap(EquipmentBaseBean::getEquipmentId, EquipmentBaseBean::getDeptSort));
        // 机组顺序
        Map<String, Integer> sortmap = oldlist.stream()
                .filter(o -> ObjectUtil.isAllNotEmpty(o.getDeptSort(), o.getSort()))
                .collect(Collectors.toMap(EquipmentBaseBean::getEquipmentId, EquipmentBaseBean::getSort));//机组顺序

        List<String> oldEqIdlist = oldlist.stream().map(EquipmentBaseBean::getEquipmentId).collect(Collectors.toList());
        List<String> newestEqIdlist = synlist.stream().map(EquipmentBaseBean::getEquipmentId).collect(Collectors.toList());

        // 找出要更新的设备
        List<EquipmentBean> updatelist = synlist.stream().filter(sy -> oldEqIdlist.contains(sy.getEquipmentId())).collect(Collectors.toList());
        // 找出要新增的设备
        List<EquipmentBean> insertlist = synlist.stream().filter(sy -> !oldEqIdlist.contains(sy.getEquipmentId())).collect(Collectors.toList());
        // 找出要停用的设备
        List<EquipmentBaseBean> stoplist = oldlist.stream().filter(sy -> !newestEqIdlist.contains(sy.getEquipmentId())).collect(Collectors.toList());
        insertlist.stream().forEach(i -> {
            i.setId(CodeTools.getCode32());
            i.setDerail(0);
        });

        if (StringUtils.isNotEmpty(insertlist)) {
            mapper.batchInsert(insertlist);
        }
        if (StringUtils.isNotEmpty(updatelist)) {
            // 设置原本的泵站、机组顺序
            updatelist.stream().forEach(u -> {
                u.setDeptSort(deptSortmap.get(u.getEquipmentId()));
                u.setDeptSort(sortmap.get(u.getEquipmentId()));
            });
            mapper.updateBatch(updatelist);
        }
        if (StringUtils.isNotEmpty(stoplist)) {
            List<String> stopEqId = stoplist.stream().map(EquipmentBaseBean::getEquipmentId).collect(Collectors.toList());
            mapper.updateDerailByEquipmentIdIn(1, stopEqId);
        }
        return StringUtils.format("新增 {} 台设备,同步 {} 台设备 --- 原来共 {} 台设备", insertlist.size(), updatelist.size(), oldEqIdlist.size());
    }


    /**
     * 基础信息列表
     *
     * @param queryBean
     * @return
     */
    @Override
    @TaskAnnotation("queryList")
    public List<EquipmentBean> queryList(SessionFactory factory, EquipmentDto queryBean) {
//        PageHelper.startPage(queryBean.getPage(), queryBean.getPageSize(), queryBean.getOrderBy());
        List<EquipmentBean> equipmentBeans = factory.getMapper(EquipmentDeMapper.class).queryList(queryBean);
        return equipmentBeans;
    }

    /**
     * 状态录入列表
     *
     * @param dto
     * @return
     */
    @Override
    @TaskAnnotation("queryStatusList")
    public List<HistoryListDto> queryStatusList(SessionFactory factory, HistoryListDto dto) {
        List<HistoryListDto> list = factory.getMapper(EquipmentHistoryMapper.class).queryStatusList(dto);
        return list;
    }

    /**
     * 变更历史列表
     *
     * @param dto
     * @return
     */
    @Override
    @TaskAnnotation("queryStatusHistoryList")
    public List<HistoryListDto> queryStatusHistoryList(SessionFactory factory, HistoryListDto dto) {
        dto.setMaxChangeTime(dto.getChangeTime());
        List<HistoryListDto> list = factory.getMapper(EquipmentHistoryMapper.class).queryStatusHistoryList(dto);
        return list;
    }


    /**
     * 跳闸列表
     *
     * @param dto
     * @return
     */
    @Override
    @TaskAnnotation("queryAccidentList")
    public List<EquipmentAccidentBean> queryAccidentList(SessionFactory factory, AccidentDto dto) {
        List<EquipmentAccidentBean> list = factory.getMapper(EquipmentAccidentMapper.class).queryByAll(dto);
        return list;
    }

    /**
     * 状态变更
     *
     * @param bean
     */
    @Override
    @TaskAnnotation("changeStatus")
    public int changeStatus(SessionFactory factory, EquipmentHistoryBean bean) {
        EquipmentHistoryMapper mapper = factory.getMapper(EquipmentHistoryMapper.class);
        BaseEqPackage(bean, factory);
        bean.setId(CodeTools.getCode32());
        int i = mapper.insertSelective(bean);
        return i;
    }

    /**
     * 设备基本信息封装
     *
     * @param bean
     * @param factory
     */
    public static void BaseEqPackage(EquipmentBaseBean bean, SessionFactory factory) {
        EquipmentBaseBean baseEq = factory.getMapper(EquipmentDeMapper.class).queryFirstByEquipmentId(bean.getEquipmentId());
        Assert.isFalse(baseEq == null, "检修设备不属于调度设备");
        bean.setEquipmentName(baseEq.getEquipmentName());
        bean.setDeptManage(baseEq.getDeptManage());
        bean.setDeptManageName(baseEq.getDeptManageName());
        bean.setEquipmentType(baseEq.getEquipmentType());
    }

    /**
     * 保存事故跳闸
     *
     * @param bean
     */
    @Override
    @TaskAnnotation("saveAccident")
    public String saveAccident(SessionFactory factory, EquipmentAccidentBean bean) {
        String id = CodeTools.getCode32();
        EquipmentAccidentMapper mapper = factory.getMapper(EquipmentAccidentMapper.class);
        AffectedLineMapper affectedlinemapper = factory.getMapper(AffectedLineMapper.class);

        if (StringUtils.isEmpty(bean.getId())) {
            bean.setId(id);
            mapper.insertSelective(bean);

            if (StringUtils.isNotEmpty(bean.getDet())) {
                bean.getDet().forEach(b -> {
                    b.setId(CodeTools.getCode32());
                    b.setAccidentId(id);
                    affectedlinemapper.insertSelective(b);
                });
            }
        } else {
            mapper.updateByPrimaryKeySelective(bean);
            affectedlinemapper.deleteByAccidentId(bean.getId());    //先删除原来的受影响线路
            if (StringUtils.isNotEmpty(bean.getDet())) {
                bean.getDet().forEach(b -> {
                    b.setId(CodeTools.getCode32());
                    b.setAccidentId(bean.getId());
                    affectedlinemapper.insertSelective(b);
                });
            }
        }
        return bean.getId();
    }

    /**
     * 线路状态汇总
     *
     * @return
     */
    @Override
    @TaskAnnotation("lineAnalysis")
    public List<AffectedLineVo> lineAnalysis(SessionFactory factory) {
        DateTime nowDate = DateUtil.parse(DateUtil.now());

        Date minChangeTime = ldtoDate(firstDayOfThisYear());//本年第一天
        Date maxChangeTime = ldtoDate(lastDayOfThisYear().plusDays(1));//明年第一天

        List<AffectedLineVo> baselist = queryBaseEq(factory, EquipmentEnum.LINE, AffectedLineVo.class);//线路 基本信息

        List<EquipmentHistoryBean> yearjxlist = factory.getMapper(EquipmentHistoryMapper.class).queryAllByChangeTimeBetween(minChangeTime, maxChangeTime);//查 一年 调度设备状态变更历史


        /** 以下面四种属于停电检修
         *     OVERHAUL(3),//大修
         *     TROUBLESHOOTING(4),//故障检修
         *     planned(5),//计划检修
         *     normal(6),//正常维护
         */
        ArrayList<Integer> tdjxlist = CollectionUtil.newArrayList(OVERHAUL.getValue(), TROUBLESHOOTING.getValue(), planned.getValue(), normal.getValue());

        //年 停电检修次数
        Map<String, List<EquipmentHistoryBean>> yearjxmap = yearjxlist.stream().filter(y -> tdjxlist.contains(y.getAfterStatus())).collect(Collectors.groupingBy(EquipmentHistoryBean::getEquipmentId));
        if (StringUtils.isNotEmpty(yearjxmap)) {
            baselist.stream().forEach(b -> {
                List<EquipmentHistoryBean> list = Optional.ofNullable(yearjxmap.get(b.getEquipmentId())).orElse(new ArrayList<>());
                b.setYearPowerCut(list.size());
            });
        }
        //月 停电检修次数
        Map<String, List<EquipmentHistoryBean>> monthjxmap = yearjxlist.stream().filter(m -> DateUtil.month(m.getChangeTime()) == DateUtil.month(nowDate) && tdjxlist.contains(m.getAfterStatus())).collect(Collectors.groupingBy(EquipmentHistoryBean::getEquipmentId));
        if (StringUtils.isNotEmpty(monthjxmap)) {
            baselist.stream().forEach(b -> {
                List<EquipmentHistoryBean> list = Optional.ofNullable(monthjxmap.get(b.getEquipmentId())).orElse(new ArrayList<>());
                b.setMonthPowerCut(list.size());
            });
        }

        List<EquipmentAccidentBean> yearTriplist = factory.getMapper(EquipmentAccidentMapper.class).queryAllByStartTimeBetween(minChangeTime, maxChangeTime);

        //年 跳闸次数
        Map<String, List<EquipmentAccidentBean>> yearTripmap = yearTriplist.stream().collect(Collectors.groupingBy(EquipmentAccidentBean::getEquipmentId));
        if (StringUtils.isNotEmpty(yearTripmap)) {
            baselist.stream().forEach(b -> {
                List<EquipmentAccidentBean> list = Optional.ofNullable(yearTripmap.get(b.getEquipmentId())).orElse(new ArrayList<>());
                b.setYeartTrip(list.size());
            });
        }

        //月 跳闸次数
        Map<String, List<EquipmentAccidentBean>> monthTripmap = yearTriplist.stream().filter(y -> DateUtil.month(y.getStartTime()) == DateUtil.month(nowDate)).collect(Collectors.groupingBy(EquipmentAccidentBean::getEquipmentId));
        if (StringUtils.isNotEmpty(monthTripmap)) {
            baselist.stream().forEach(b -> {
                List<EquipmentAccidentBean> list = Optional.ofNullable(monthTripmap.get(b.getEquipmentId())).orElse(new ArrayList<>());
                b.setMonthTrip(list.size());
            });
        }
        return baselist;
    }

    /**
     * 机组线路汇总
     *
     * @return
     */
    @Override
    @TaskAnnotation("unitAnalysis")
    public List<AffectedUnitVo> unitAnalysis(SessionFactory factory) {
        EquipmentHistoryMapper mapper = factory.getMapper(EquipmentHistoryMapper.class);

        List<AffectedUnitVo> baselist = queryBaseEq(factory, EquipmentEnum.UNIT, AffectedUnitVo.class);//线路 基本信息

        List<HistoryListDto> statuslist = queryStatusList(factory, new HistoryListDto(EquipmentEnum.UNIT.getValue()));
        Map<String, Integer> newStatusmap = new HashMap<>();
        statuslist.forEach(s -> newStatusmap.put(s.getEquipmentId(), s.getAfterStatus()));//机组最新状态

        List<HistoryListDto> lastOverhaulTime = mapper.queryStatusListByBeforeStatus(new HistoryListDto(EquipmentEnum.UNIT.getValue(), OVERHAUL.getValue()));
        Map<String, String> lastoverhaulmap = lastOverhaulTime.stream().collect(Collectors
                .toMap(HistoryListDto::getEquipmentId,
                        dbrs -> Optional.ofNullable(dbrs).map(c -> DateUtil.format(c.getChangeTime(), "yyyy-MM-dd HH:mm:ss")).orElse(""),
                        (q1, q2) -> q1));//机组最近大修完成时间

        DateTime nowDate = DateUtil.parse(DateUtil.now());

        Date minYearChangeTime = ldtoDate(firstDayOfThisYear());//本年第一天
        Date maxYearChangeTime = ldtoDate(lastDayOfThisYear().plusDays(1));//明年第一天

        Date minMonthChangeTime = ldtoDate(firstDayOfThisMonth());//本月第一天
        Date maxMonthChangeTime = ldtoDate(lastDayOfThisMonth().plusDays(1));//明月第一天

        //所有机组本年记录
        List<EquipmentHistoryBean> yearNotDisabledlist = mapper.queryAllByChangeTimeBetween(minYearChangeTime, maxYearChangeTime);//查 本年 调度设备状态变更历史
        //所有机组本月记录
        List<EquipmentHistoryBean> monthNotDisabledlist = mapper.queryAllByChangeTimeBetween(minMonthChangeTime, maxMonthChangeTime);//查 本月 调度设备状态变更历史

        baselist.stream().forEach(v -> {
            //单个机组年记录
            List<EquipmentHistoryBean> yearlist = Optional.ofNullable(yearNotDisabledlist.stream().filter(y -> v.getEquipmentId().equals(y.getEquipmentId())).collect(Collectors.toList())).orElse(new ArrayList<>());
            //单个机组月记录
            List<EquipmentHistoryBean> monthlist = Optional.ofNullable(monthNotDisabledlist.stream().filter(y -> v.getEquipmentId().equals(y.getEquipmentId())).collect(Collectors.toList())).orElse(new ArrayList<>());

            BigDecimal monthDisabled = getUnitDisableTime(factory, nowDate, minMonthChangeTime, maxMonthChangeTime, v, monthlist, EquipmentEnum.UNIT);//不可用累计时间(小时)-本月
            BigDecimal yeartDisabled = getUnitDisableTime(factory, nowDate, minYearChangeTime, maxMonthChangeTime, v, yearlist, EquipmentEnum.UNIT);//不可用累计时间(小时)-本年

            v.setAfterStatus(newStatusmap.get(v.getEquipmentId()));
            v.setMonthDisabled(monthDisabled);
            v.setYeartDisabled(yeartDisabled);
            v.setLastOverhaulTime(lastoverhaulmap.get(v.getEquipmentId()));
        });
        return baselist;
    }

    /**
     * 主变状态汇总
     *
     * @return
     */
    @Override
    @TaskAnnotation("tranAnalysis")
    public List<AffectedTranVo> tranAnalysis(SessionFactory factory) {

        EquipmentHistoryMapper mapper = factory.getMapper(EquipmentHistoryMapper.class);

        List<AffectedTranVo> baselist = queryBaseEq(factory, EquipmentEnum.TRAN, AffectedTranVo.class);//线路 基本信息

//        List<HistoryListDto> statuslist = queryStatusList(factory, new HistoryListDto(EquipmentEnum.UNIT.getValue()));
//        Map<String, Integer> newStatusmap = new HashMap<>();
//        statuslist.forEach(s -> newStatusmap.put(s.getEquipmentId(), s.getAfterStatus()));//主变最新状态

        DateTime nowDate = DateUtil.parse(DateUtil.now());

        Date minYearChangeTime = ldtoDate(firstDayOfThisYear());//本年第一天
        Date maxYearChangeTime = ldtoDate(lastDayOfThisYear().plusDays(1));//明年第一天

        Date minMonthChangeTime = ldtoDate(firstDayOfThisMonth());//本月第一天
        Date maxMonthChangeTime = ldtoDate(lastDayOfThisMonth().plusDays(1));//明月第一天

        //所有主变本年记录
        List<EquipmentHistoryBean> yearNotDisabledlist = mapper.queryAllByChangeTimeBetween(minYearChangeTime, maxYearChangeTime);//查 本年 调度设备状态变更历史
        //所有主变本月记录
        List<EquipmentHistoryBean> monthNotDisabledlist = mapper.queryAllByChangeTimeBetween(minMonthChangeTime, maxMonthChangeTime);//查 本月 调度设备状态变更历史

        baselist.stream().forEach(v -> {
            //单个主变年记录
            List<EquipmentHistoryBean> yearlist = Optional.ofNullable(yearNotDisabledlist.stream().filter(y -> v.getEquipmentId().equals(y.getEquipmentId())).collect(Collectors.toList())).orElse(new ArrayList<>());
            //单个主变月记录
            List<EquipmentHistoryBean> monthlist = Optional.ofNullable(monthNotDisabledlist.stream().filter(y -> v.getEquipmentId().equals(y.getEquipmentId())).collect(Collectors.toList())).orElse(new ArrayList<>());

            BigDecimal monthDisabled = getUnitDisableTime(factory, nowDate, minMonthChangeTime, maxMonthChangeTime, v, monthlist, EquipmentEnum.UNIT);//不可用累计时间(小时)-本月
            BigDecimal yeartDisabled = getUnitDisableTime(factory, nowDate, minYearChangeTime, maxMonthChangeTime, v, yearlist, EquipmentEnum.UNIT);//不可用累计时间(小时)-本年

//            v.setAfterStatus(newStatusmap.get(v.getEquipmentId()));
            v.setMonthDisabled(monthDisabled);
            v.setYeartDisabled(yeartDisabled);
        });

        return baselist;
    }

    /**
     * 基本设备
     *
     * @param factory
     * @param enm     数据字典（dispatch_type）:主变TRAN、线路LINE、机组UNIT
     * @return
     */
    private <T extends EquipmentBaseBean> List<T> queryBaseEq(SessionFactory factory, EquipmentEnum enm, Class<T> clazz) {
        List<EquipmentBaseBean> baselist = factory.getMapper(EquipmentDeMapper.class).queryAll();//查所有设备
//        baselist.stream().forEach(b ->{
//            b.setAfterStatus(afterStatusEqIdmap.get(b.getEquipmentId()));//补充设备最新状态
//        });
        if (StringUtils.isNotEmpty(baselist)) {
            List<HistoryListDto> historyListDtos = this.queryStatusList(factory, new HistoryListDto(enm.getValue()));//查最新设备状态
            Map<String, Integer> afterStatusEqIdmap = historyListDtos.stream().filter(d -> d.getAfterStatus() != null).collect(Collectors.toMap(HistoryListDto::getEquipmentId, HistoryListDto::getAfterStatus,(key1,key2)->key1));

            List<EquipmentBaseBean> filterlist = baselist.stream().filter(f -> f.getEquipmentType().equals(enm.getValue())).collect(Collectors.toList());
            List<T> list = new ArrayList<>();
            filterlist.stream().forEach(b -> {
                b.setAfterStatus(afterStatusEqIdmap.get(b.getEquipmentId()));//补充设备最新状态
                list.add(Convert.convert(clazz, b));
            });
            return list;
        }
        return new ArrayList<>();
    }


    /**
     * 计算机组不可用时间
     *
     * @param factory
     * @param curDate   当前时间
     * @param startDate 开始时间
     * @param endDate   结束时间
     * @param baseUnit  设备
     * @param unitList  设备的变更记录
     * @return 不可用时间
     */
    private BigDecimal getUnitDisableTime(SessionFactory factory, Date curDate, Date startDate, Date endDate, EquipmentBaseBean baseUnit, List<EquipmentHistoryBean> unitList, EquipmentEnum eumtype) {
        List<Integer> common = new ArrayList<>();
        if (eumtype.getValue().equals(EquipmentEnum.UNIT.getValue())) {
            common = CollectionUtil.newArrayList(AVA.getValue(), OPERATION.getValue());//运行、可用状态 为可用
        }
        if (eumtype.getValue().equals(EquipmentEnum.TRAN.getValue())) {
            common = CollectionUtil.newArrayList(AVA.getValue(), OPERATION.getValue(), HOTSTANDBY.getValue(), COLD.getValue());//运行、可以、热备用、冷备用状态 为可用
        }

        BigDecimal disabledTime = BigDecimal.ZERO;
        if (unitList == null || unitList.size() == 0) {
            //当前月没有记录， 需要查找最近的一条记录
            EquipmentHistoryBean record = factory.getMapper(EquipmentHistoryMapper.class).queryMaxChangeIimeFirstByEquipmentId(baseUnit.getEquipmentId());
            if (record != null) {
                //true 不可用
                if (!record.getAfterStatus().equals(AVA.getValue())) {
                    //(当前时间 - 开始时间) / 小时
                    BigDecimal divide = (BigDecimal.valueOf(curDate.getTime())).subtract(BigDecimal.valueOf(startDate.getTime())).divide(convertTime, 2, BigDecimal.ROUND_DOWN);
                    disabledTime = disabledTime.add(divide);
                }
            }
        } else {
            for (int i = 0; i < unitList.size(); i++) {
                //第一条记录要用月初时间计算
                if (i == 0) {
                    if (!common.contains(Optional.ofNullable(unitList.get(i).getBeforeStatus()).orElse(0))) {
//                    if (!Optional.ofNullable(unitList.get(i).getBeforeStatus()).orElse(0).equals(AVA.getValue())) {
                        // (记录变更时间 - 开始时间) / 小时
                        BigDecimal divide = (BigDecimal.valueOf(unitList.get(i).getChangeTime().getTime()).subtract(BigDecimal.valueOf(startDate.getTime()))).divide(convertTime, 2, BigDecimal.ROUND_DOWN);
                        disabledTime = disabledTime.add(divide);
                    }
                    continue;
                }
                if (i != 0 && (i + 1) == unitList.size()) {
                    if (!common.contains(Optional.ofNullable(unitList.get(i).getBeforeStatus()).orElse(0))) {
//                    if (!unitList.get(i).getBeforeStatus().equals(AVA.getValue())) {
                        // (记录变更时间 - 上一次记录变更时间) / 小时
                        BigDecimal divide = (BigDecimal.valueOf(unitList.get(i).getChangeTime().getTime()).subtract(BigDecimal.valueOf(unitList.get(i - 1).getChangeTime().getTime()))).divide(convertTime, 2, BigDecimal.ROUND_DOWN);
                        disabledTime = disabledTime.add(divide);
                    }
                }
                //最后一条记录 要用月尾时间计算
                if ((i + 1) == unitList.size()) {
                    if (!common.contains(unitList.get(i).getAfterStatus())) {
//                    if (unitList.get(i).getAfterStatus().equals(AVA.getValue())) {
                        // (结束时间 - 记录变更时间) / 小时
                        BigDecimal divide = (BigDecimal.valueOf(endDate.getTime()).subtract(BigDecimal.valueOf(unitList.get(i).getChangeTime().getTime()))).divide(convertTime, 2, BigDecimal.ROUND_DOWN);
                        disabledTime = disabledTime.add(divide);
                    }
                }
            }
        }
//        return Math.round(disabledTime * 100) / 100d;
        return disabledTime;
    }


    @Override
    @TaskAnnotation("getUnitStartLogParameter")
    public List<UnitSynDto> getUnitStartLogParameter(SessionFactory factory, List<UnitRelationDo> unitrelist) {

        EquipmentDeMapper mapper = factory.getMapper(EquipmentDeMapper.class);
        StartLogBeanMapper startlogmapper = factory.getMapper(StartLogBeanMapper.class);

        unitrelist.stream().forEach(UnitRelationDo::splitToDescription);// 根据描述分割出数据源
        Map<String, String> quidDBmap = unitrelist.stream().collect(Collectors.toMap(UnitRelationDo::getKey, UnitRelationDo::getDbs));//台账id 与 数据源
        Map<String, String> quidDpNamemap = unitrelist.stream().collect(Collectors.toMap(UnitRelationDo::getKey, UnitRelationDo::getValue));//台账id 与 数据数据库dpName

        List<UnitSynDto> unitSynlist = startlogmapper.getLastSynTime();//获取机组和机组最后同步时间
        unitSynlist.stream().forEach(u -> {
            u.setDpName(quidDpNamemap.get(u.getEquipmentId()));// 匹配机组的的dpName
            u.setDbs(quidDBmap.get(u.getEquipmentId()));// 匹配台账id
            u.convenTime();// eam系统时间 转换 监控数据库时间

        });
        //过滤没有配置数据源的泵站
        List<UnitSynDto> unitSynFilterlist = unitSynlist.stream().filter(u -> StringUtils.isNotBlank(u.getDbs())).collect(Collectors.toList());

        return unitSynFilterlist;
    }


}
